<template>
  <div class="video-container">
    <van-nav-bar :title="'菜谱详情'" fixed left-arrow @click-left="$router.back()">
      <template #right>
        <div class="right-icon">
          <span class="collect-like-icon" v-if="isLike"></span>
          <span class="collect-icon" @click="like" v-else></span>
          <span class="recipe-icon"></span>
        </div>
      </template>
    </van-nav-bar>
    <div class="header" v-if="hasVideo" @touchend="showBtn">
      <video class="video" ref="video" :src="videoUrl" height="200" width="100%" @timeupdate="currentTime" @loadedmetadata="setDuration" @ended="resetDuration"></video>
      <div class="pic" :style="{ backgroundImage: curRecipeDetail.imageid ? `url(http://pic.angelboy.cn/web/${curRecipeDetail.imageid}.jpg)` : '' }" ref="pic"></div>
      <div ref="play-pause">
        <span v-if="playing" class="pause" @click="pause"></span>
        <span v-else class="play" @click="play"></span>
        <div class="process" ref="progress">
          <span class="start-time">{{ curTime }}</span>
          <div class="progress">
            <input ref="process" type="range" min="0" max="100" :value="curValue" @change="setCurrentTime" />
          </div>
          <span class="end-time">{{ duration }}</span>
        </div>
      </div>
    </div>
    <div class="food-image" v-else>
      <img :src="curRecipeDetail.imageid ? `http://pic.angelboy.cn/web/${curRecipeDetail.imageid}.jpg` : ''" />
    </div>
    <!-- 菜谱信息  -->
    <FootLooksLike :name="curRecipeDetail.name" :likeCount="likeNum" :viewCount="collectionNum" :authorName="curRecipeDetail.authorname" :description="curRecipeDetail.description"> </FootLooksLike>
    <!-- 菜谱材料 -->
    <div class="foods-materials">
      <div class="title-tip">
        <span>材料</span>
        <span>加入菜篮子</span>
      </div>
      <FoodMaterials :foodsMaterials="curRecipeDetail.materialList"></FoodMaterials>
    </div>
    <!-- 步骤 -->
    <Footsteps :stepList="curRecipeDetail.stepList"></Footsteps>

    <!-- 小贴士 -->
    <TipsCom :tips="tips" v-if="tips.length > 0"></TipsCom>
  </div>
</template>

<script>
import request from '@/utils/request/request'
import FoodMaterials from '@/components/media/FoodMaterials'
import FootLooksLike from '@/components/details-view/FootLooksLike.vue'
import Footsteps from '@/components/details-view/Footsteps'
import TipsCom from '@/components/details-view/TipsCom'
import local from '@/utils/localStorage/index.js'
export default {
  props: ['id'],
  components: {
    FoodMaterials,
    FootLooksLike,
    Footsteps,
    TipsCom
  },
  data() {
    return {
      timer: null,
      duration: '',
      curTime: '',
      curValue: 0,
      videoUrl: '',
      isLike: false,
      hasVideo: false,
      curRecipeDetail: {},
      tips: [],
      playing: false,
      isPlaying: false,
      isPlayEnd: true,
      likeNum: this.$route.query.likeNum,
      collectionNum: this.$route.query.collectionNum
    }
  },
  methods: {
    like() {
      if (this.isLike) return
      let likeRecipe = {
        id: this.curRecipeDetail.id,
        imageid: this.curRecipeDetail.imageid,
        likeNum: this.likeNum,
        collectionNum: this.collectionNum,
        title: this.curRecipeDetail.name,
        isVideo: this.hasVideo
      }
      local.setData(likeRecipe)
      this.isLike = true
    },
    // 播放结束之后重置视频
    resetDuration() {
      const progress = this.$refs.progress
      const btn = this.$refs['play-pause']
      // 获取音频总时长
      const video = this.$refs.video
      const pic = this.$refs.pic
      pic.style.display = 'none'
      this.isPlaying = false
      this.playing = false
      video.currentTime = 0
      pic.style.display = 'block'
      progress.style.opacity = 0
      this.isPlayEnd = true
      btn.classList.forEach((value) => {
        console.log(value)
        if (value == 'hide') {
          btn.classList.remove(value)
        }
      })
    },
    setDuration() {
      const video = this.$refs.video
      console.log(video.duration)
      //计算音频分钟数
      let minute = Math.floor(video.duration / 60)
      let seconds = Math.floor(video.duration % 60)
      minute = minute < 10 ? '0' + minute : minute
      seconds = seconds < 10 ? '0' + seconds : seconds
      this.duration = minute + ':' + seconds
    },
    currentTime() {
      const video = this.$refs.video
      let minute = Math.floor(video.currentTime / 60)
      let seconds = Math.floor(video.currentTime % 60)
      minute = minute < 10 ? '0' + minute : minute
      seconds = seconds < 10 ? '0' + seconds : seconds
      this.curTime = minute + ':' + seconds
      if (video.duration) {
        // 计算进度条value
        this.curValue = Math.floor((video.currentTime / video.duration) * 100)
      }
    },
    setCurrentTime() {
      const process = this.$refs.process
      const video = this.$refs.video
      //计算当前播放的时间
      if (video.duration) {
        let currentTime = (process.value / 100) * video.duration
        video.currentTime = currentTime
      }
    },
    //播放视频
    play() {
      const progress = this.$refs.progress
      // 获取音频总时长
      const video = this.$refs.video
      const pic = this.$refs.pic
      pic.style.display = 'none'
      if (!this.isPlaying) {
        video.load()
      }
      video.play()
      this.isPlayEnd = false
      this.isPlaying = true
      this.playing = true
      progress.style.opacity = 1
      this.$nextTick(() => {
        const btn = this.$refs['play-pause']
        btn.classList.forEach((value) => {
          if (value == 'show') {
            btn.classList.remove(value)
          }
        })
        setTimeout(() => {
          btn.classList.add('hide')
        }, 2000)
      })
    },
    //暂停视频
    pause() {
      const video = this.$refs.video
      video.pause()
      this.playing = false
    },
    // 显示隐藏播放按钮和暂停按钮
    showBtn() {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (this.isPlayEnd) return
      const btn = this.$refs['play-pause']
      btn.classList.remove('hide')
      this.timer = setTimeout(() => {
        btn.classList.add('hide')
      }, 2000)
    },
    // saveHistoryWatch数据
    saveHistoryWatch() {
      //获取本地数据
      let historyWatch = JSON.parse(localStorage.getItem('historyWatch')) || []
      for (let i = 0; i < historyWatch.length; i++) {
        if (historyWatch[i].id == this.curRecipeDetail.id) {
          return
        }
      }
      const currentWatch = {
        id: this.curRecipeDetail.id,
        imageid: this.curRecipeDetail.imageid,
        likeNum: this.likeNum,
        collectionNum: this.collectionNum,
        title: this.curRecipeDetail.name,
        authorname: this.curRecipeDetail.authorname
      }
      // 如果没有看过就将当前数据进行保存
      historyWatch.unshift(currentWatch)
      // 将数据进行保存
      localStorage.setItem('historyWatch', JSON.stringify(historyWatch))
    },

    // 发起请求获取当前菜谱是否为视频
    async requestIsVideo(toast) {
      /*
      是否有视频请求地址：http://120.55.28.235/public/hasVideoOrNot.shtml
      请求方式：post
      请求参数：{
        listStr： 当前菜谱的id
      }
      */
      const {
        data: { list: res }
      } = await request({
        url: '/public/hasVideoOrNot.shtml',
        method: 'post',
        data: {
          listStr: this.id
        }
      })
      this.hasVideo = res[0].hasVideo
      this.requestRecipeDetail(toast)
    },

    //发起请求获取详情菜谱详情的数据
    async requestRecipeDetail(toast) {
      /*
        请求路径：http://120.55.28.235/public/getRecipeListByIds.shtml
        请求方式： post
        请求参数：{
          ids： 当前菜谱的id
        }
      */
      const {
        data: { list: res }
      } = await request({
        url: '/public/getRecipeListByIds.shtml',
        method: 'post',
        data: {
          ids: this.id
        }
      })
      this.curRecipeDetail = res[0]
      this.saveHistoryWatch()
      if (res[0].video) {
        this.videoUrl = res[0].video.url
      }

      if (this.curRecipeDetail.tipList.length > 0 && this.curRecipeDetail.tipList[0]['details'] != '') {
        this.tips = this.curRecipeDetail.tipList[0].details.split('\n')
      }
      toast && toast.clear()
    }
  },
  created() {
    const toast = this.$toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    })
    this.requestIsVideo(toast)
    let data = local.getData()
    data.filter((item) => item.id == this.id).length > 0 ? (this.isLike = true) : (this.isLike = false)
  },
  // 在mounted函数中实现看过的食谱添加到本地
  mounted() {}
}
</script>

<style lang="less" scoped>
.video-container {
  padding-top: 46px;

  .food-image {
    height: 200px;

    img {
      height: 100%;
      width: 100%;
    }
  }

  .header {
    width: 100%;
    height: 200px;
    position: sticky;
    left: 0;
    top: 46px;
    z-index: 999;
    background-color: #fff;
    .video {
      width: 100%;
      object-fit: fill;
      background-color: #000000;
    }
    .pic {
      height: 100%;
      background-size: 100% 100%;
      background-repeat: no-repeat;
    }

    div {
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 1000000;

      .process {
        height: 30px;
        position: absolute;
        top: 170px;
        left: 50%;
        opacity: 0;
        display: flex;
        padding: 0 15px;
        color: white;
        box-sizing: border-box;
        justify-content: space-between;
        align-items: center;
        background-image: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.3));
        transform: translateX(-50%);

        input {
          height: 5px;
          width: 240px;
        }
      }

      &.hide {
        display: none;
      }

      .play,
      .pause {
        width: 40px;
        height: 40px;
        border-radius: 999px;
        background-position: center;
        background-size: 20px 20px;
        background-repeat: no-repeat;
        background-color: rgba(0, 0, 0, 0.5);
      }

      .play {
        background-image: url('@/assets/home/play.png');
      }
      .pause {
        background-image: url('@/assets/home/pause.png');
      }
    }
  }
  .foods-materials {
    padding: 10px 20px;

    .title-tip {
      display: flex;
      padding: 10px 0;
      justify-content: space-between;
      align-items: center;

      span:first-child {
        font-size: 16px;
        font-weight: 700;
        color: #444;
      }
      span:last-child {
        font-size: 12px;
        color: orange;
      }
    }
  }

  .right-icon {
    display: flex;
    align-items: center;

    .collect-icon,
    .collect-like-icon,
    .recipe-icon {
      width: 20px;
      height: 20px;
      background-size: cover;
      background-repeat: no-repeat;
      background-position: center;

      &.collect-like-icon {
        margin-right: 15px;
        background-image: url('@/assets/home/bottom_collect_yellow.png');
      }
      &.collect-icon {
        margin-right: 15px;
        background-image: url('@/assets/additional/ic_home_collect.png');
      }

      &.recipe-icon {
        background-image: url('@/assets/additional/icon_recipe_basket_gray.png');
      }
    }
  }

  .van-nav-bar {
    z-index: 999;
  }
  /deep/.van-nav-bar__title {
    font-weight: 600;
    color: #999;
    font-size: 18px;
  }
  /deep/.van-icon {
    color: #aeaeae;
    font-size: 20px;
  }
}
</style>
